/*
 * Copyright(c)2018,2025,guowenmeng24@163.comAllrightsreserved.
 */
package com.ddd.adapter.event.consumer.handler;

import com.ddd.app.operationlog.service.OperationLogServiceImpl;
import com.ddd.client.user.dto.event.LoginEvent;
import com.ddd.domain.operationLog.model.OperationLogEntity;
import com.ddd.infrastructure.common.utils.JakartaServletUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * LoginHandler
 * 举个不太恰当的使用发布事件的例子
 *@author guowm
 *@date 2025/02/10
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class LoginHandler {

    final OperationLogServiceImpl operationLogService;

    @EventListener
    @Async
    public void handle(LoginEvent event) {
        log.info("LoginHandler.handle()：{}", event);
        final HttpServletRequest httpServletRequest = JakartaServletUtil.getRequest();
        // 创建 ObjectMapper 对象
        ObjectMapper objectMapper = new ObjectMapper();
        OperationLogEntity operationLogEntity = new OperationLogEntity();

        operationLogEntity.setIp(JakartaServletUtil.getClientIP(httpServletRequest));
        operationLogEntity.setLocation("");
        operationLogEntity.setMethod(httpServletRequest.getMethod());
        operationLogEntity.setUri(httpServletRequest.getRequestURI());
        operationLogEntity.setWasteTime(0);
        operationLogEntity.setRequestBody("{}");
        try {
            operationLogEntity.setRequestParam(objectMapper.writeValueAsString(httpServletRequest.getParameterMap()));
            // 将对象转换为 JSON 字符串
            operationLogEntity.setResponseResult(objectMapper.writeValueAsString(event));
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        operationLogService.save(operationLogEntity);
    }

}